<?php

namespace app\award;

use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\product\ProductAreaList;
use app\models\Queue;
use app\models\SetProductCommission;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserAddress;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\models\UserBalance;
use app\models\UserStore;
use app\models\UserStoreLog;
use app\services\Chain;
use yii\helpers\ArrayHelper;

class Award
{
    protected $user;
    protected $order;
    protected $set;

    protected $items;

    protected $product_id;

    // 总金额
    protected $amount;

    public function __construct(Order $order)
    {
        $this->order = $order;
        $this->user = User::findOne(['id' => $order->user_id]);
        $this->set = SetUserUp::getLastOne();


        $this->items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $first_order_item = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->orderBy(['id' => SORT_ASC])
            ->limit(1)
            ->one();
        $this->product_id = $product_id = $first_order_item->product_id;

        $this->amount = $this->order->total_pay - $this->order->total_freight;

        // 报单区
        if (ProductAreaList::checkInArea($product_id, Product::$areaMap['REPORT'])) {
            $this->bao();
            $this->profit();
        }

        // 复购区
        // 复购从平台走, 有差价奖, 没有同级奖
        if (ProductAreaList::checkInArea($product_id, Product::$areaMap['REPEAT'])) {
            $this->repeat();
            $this->profit();
        }
    }



    public function bao()
    {
        $type = 10;
        $name = '推荐奖';

        $type2 = 11;
        $name2 = '平级奖';

        $has_vip1 = false;
        $has_vip2 = false;
        $has_vip2_2 = false;
        $has_vip3 = false;
        $has_vip3_2 = false;
        $has_vip4 = false;
        $has_vip4_2 = false;

        $diff_vip1 = 0;
        $diff_vip2 = 0;
        $diff_vip2_2 = 0;
        $diff_vip3 = 0;
        $diff_vip3_2 = 0;
        $diff_vip4 = 0;
        $diff_vip4_2 = 0;

        $chain = Chain::getReferrerChain($this->order->user_id, [
            UserLevel::$keys['vip1'],
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3'],
            UserLevel::$keys['vip4']
        ], true);

        $commission = SetProductCommission::findOne(['product_id' => $this->product_id])->toArray();

        foreach ($chain as $user) {
            if ((!$has_vip1 && !$has_vip2 && !$has_vip3 && !$has_vip4) && $user->level == UserLevel::$keys['vip1']) {
                $diff_vip1 = $commission['r1'];
                $this->saveCommission($user->id, $diff_vip1, $type, $name);
                $has_vip1 = true;
            }

            if (((!$has_vip2 || !$has_vip2_2) && !$has_vip3 && !$has_vip4) && $user->level == UserLevel::$keys['vip2']) {
                if ($diff_vip2 == 0) {
                    $diff_vip2 = $commission['r2'];
                    $diff_vip2 -= $diff_vip1;
                    $this->saveCommission($user->id, $diff_vip2, $type, $name);
                    $has_vip2 = true;
                } else {
                    $this->saveCommission($user->id, $commission['e2'], $type2, $name2);
                    $has_vip2_2 = true;
                }
            }
            if (((!$has_vip3 || !$has_vip3_2) && !$has_vip4) && $user->level == UserLevel::$keys['vip3']) {
                if ($diff_vip3 == 0) {
                    $diff_vip3 = $commission['r3'];
                    $diff_vip3 -= $diff_vip2 + $diff_vip1;
                    // $diff_vip3 -= $diff_vip2;
                    $this->saveCommission($user->id, $diff_vip3, $type, $name);
                    $has_vip3 = true;
                } else {
                    $this->saveCommission($user->id, $commission['e3'], $type2, $name2);
                    $has_vip3_2 = true;
                }
            }
            if ((!$has_vip4 || !$has_vip4_2) && $user->level == UserLevel::$keys['vip4']) {
                if ($diff_vip4 == 0) {
                    $diff_vip4 = $commission['r4'];
                    $diff_vip4 -= $diff_vip3 + $diff_vip2 + $diff_vip1;
                    // $diff_vip4 -= $diff_vip3 + $diff_vip2;
                    $this->saveCommission($user->id, $diff_vip4, $type, $name);
                    $has_vip4 = true;
                } else {
                    $this->saveCommission($user->id, $commission['e4'], $type2, $name2);
                    $has_vip4_2 = true;
                    break;
                }
                // break;
            }
        }
    }

    public function repeat()
    {
        $type = 20;
        $name = '复购奖';

        $has_vip2 = false;
        $has_vip3 = false;
        $has_vip4 = false;

        $diff_vip2 = 0;
        $diff_vip3 = 0;
        $diff_vip4 = 0;

        $chain = Chain::getReferrerChain($this->order->user_id, [
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3'],
            UserLevel::$keys['vip4']
        ], true);

        foreach ($chain as $user) {

            if ((!$has_vip2 && !$has_vip3 && !$has_vip4) && $user->level == UserLevel::$keys['vip2']) {
                $diff_vip2 = $this->_diff('vip2');
                $this->saveCommission($user->id, $diff_vip2, $type, $name);
                $has_vip2 = true;
            }
            if ((!$has_vip3 && !$has_vip4) && $user->level == UserLevel::$keys['vip3']) {
                $diff_vip3 = $this->_diff('vip3');
                $diff_vip3 -= $diff_vip2;
                $this->saveCommission($user->id, $diff_vip3, $type, $name);
                $has_vip3 = true;
            }
            if ((!$has_vip4) && $user->level == UserLevel::$keys['vip4']) {
                $diff_vip4 = $this->_diff('vip4');
                $diff_vip4 -= $diff_vip2 + $diff_vip3;
                $this->saveCommission($user->id, $diff_vip4, $type, $name);
                $has_vip4 = true;
                break;
            }
        }
    }

    private function _diff($diff_key)
    {
        $order_items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $sum = 0;

        foreach ($order_items as $item) {
            $product = SetProductCommission::findOne(['product_id' => $item->product_id])->toArray();
            // $sum += ($item['price'] - $product[$diff_key]) * $item['quantity'];
            $sum += ($product['vip1'] - $product[$diff_key]) * $item['quantity'];
        }

        return $sum;
    }

    // 分红
    public function profit()
    {
        // 大星级包含小星级的

        // 之前做的分红和团队无关, 现在必须是团队下面的
        $ids = Chain::getReferrerChain($this->order->user_id);
        $ids = ArrayHelper::getColumn($ids, 'id');

        $star5 = User::find()
            ->where(['>=', 'level', UserLevel::$keys['vip1']])
            ->andWhere(['>=', 'star', 5])
            ->andWhere(['id' => $ids])
            ->asArray()
            ->all();
        $star4 = User::find()
            ->where(['>=', 'level', UserLevel::$keys['vip1']])
            ->andWhere(['>=', 'star', 4])
            ->andWhere(['id' => $ids])
            ->asArray()
            ->all();
        $star3 = User::find()
            ->where(['>=', 'level', UserLevel::$keys['vip1']])
            ->andWhere(['>=', 'star', 3])
            ->andWhere(['id' => $ids])
            ->asArray()
            ->all();
        $star2 = User::find()
            ->where(['>=', 'level', UserLevel::$keys['vip1']])
            ->andWhere(['>=', 'star', 2])
            ->andWhere(['id' => $ids])
            ->asArray()
            ->all();
        $star1 = User::find()
            ->where(['>=', 'level', UserLevel::$keys['vip1']])
            ->andWhere(['>=', 'star', 1])
            ->andWhere(['id' => $ids])
            ->asArray()
            ->all();

        $box = 0;
        foreach ($this->items as $item) {
            $count = (int)Product::find()
                ->where(['id' => $item['product_id']])
                ->select(['box_count'])
                ->scalar();
            $box += $count * $item['quantity'];
        }

        if ($star1) {
            $commission = $this->set->s1;
            $commission *= $box;
            $this->_star($star1, $commission, 1);
        }
        if ($star2) {
            $commission = $this->set->s2;
            $commission *= $box;
            $this->_star($star2, $commission, 2);
        }
        if ($star3) {
            $commission = $this->set->s3;
            $commission *= $box;
            $this->_star($star3, $commission, 3);
        }
        if ($star4) {
            $commission = $this->set->s4;
            $commission *= $box;
            $this->_star($star4, $commission, 4);
        }
        if ($star5) {
            $commission = $this->set->s5;
            $commission *= $box;
            $this->_star($star5, $commission, 5);
        }
    }

    private function _star($list, $commission, $star = 0)
    {
        $type = 30;
        $name = '分红';

        $count = count($list);

        // 计算每个人的团队盒数, 占总盒数的比例
        $box = 0;
        $data = [];
        foreach ($list as &$item) {
            $ids = Chain::getChildrenAll($item['id']);
            $ids = ArrayHelper::getColumn($ids, 'id');
            $ids = array_merge($ids, [$item['id']]);

            $item['box'] = Up::getBox($ids);
            $box += $item['box'];

            // 一定要用data重新接收下
            $data[] = $item;
        }

        // var_dump($box, $list, $star);exit;

        foreach ($data as $item) {

            // 计算占总盒数的比例
            // $ratio = (int)($item['box'] / $box * 100) / 100;
            $ratio = $item['box'] / $box;

            // $this->saveCommission($item['id'], $commission / $count, $type, $name);
            $this->saveCommission($item['id'], $commission * $ratio, $type, $name . $star . '星');
        }
    }

    // 保存佣金 (await balance)
    protected function saveCommission($user_id, $balance, $type, $name, $status = 1)
    {
        if ($balance >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $this->order->user_id;
            $model->order_id = $this->order->id;
            $model->balance = $balance;
            $model->status = $status;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();
            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                if ($status == 1) {
                    $account->balance += $balance;
                } else {
                    $account->await_balance += $balance;
                }

                $account->save();
            }

            // balance logs
            if ($status == 1) {
                UserBalance::addLog($model->user_id,
                    $account->balance, $model->balance, $account->balance + $model->balance, '返佣', $this->order->id);
            }
        }
    }

    protected function saveScore($user_id, $platform_ticket, $type, $name, $status = 1)
    {
        if ($platform_ticket >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $this->order->user_id;
            $model->order_id = $this->order->id;
            $model->balance = 0;
            $model->status = $status;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->platform_ticket = $platform_ticket;
            $model->save();

            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                $account->platform_ticket += $platform_ticket;
                $account->save();
            }
        }
    }
}